package com.casstime.ec.cloud.discount.restful;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.casstime.commons.service.exception.HttpMessageException;
import com.casstime.ec.cloud.discount.client.Userv2Client;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionFlowingMapper;
import com.casstime.ec.cloud.discount.dao.giftPromotion.GiftPromotionUpdateRecordMapper;
import com.casstime.ec.cloud.discount.model.DiscountRuleParam;
import com.casstime.ec.cloud.discount.services.GiftProductDAOService;
import com.casstime.ec.cloud.discount.services.GiftPromotionDAOService;
import com.casstime.ec.cloud.discount.util.CassAssert;
import com.casstime.ec.cloud.service.GenericService;
import com.casstime.ec.cloud.service.giftPromotion.GiftPromotionService;
import com.casstime.ec.cloud.spi.PagedModels;
import com.casstime.ec.cloud.user.spi.models.User;
import com.casstime.ec.cloud.values.amountPromotion.AmountPromotionCompany;
import com.casstime.ec.cloud.values.amountPromotion.AmountPromotionQueryRequest;
import com.casstime.ec.cloud.values.amountPromotion.enums.DiscountConfigValueEnum;
import com.casstime.ec.cloud.values.giftPromotion.GiftDeduction;
import com.casstime.ec.cloud.values.giftPromotion.GiftDeductionGift;
import com.casstime.ec.cloud.values.giftPromotion.GiftProduct;
import com.casstime.ec.cloud.values.giftPromotion.GiftProductAudit;
import com.casstime.ec.cloud.values.giftPromotion.GiftProductUpdateRecord;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotion;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionFlowing;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionFlowingRequest;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionGiftVO;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionProduct;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionRequest;
import com.casstime.ec.cloud.values.giftPromotion.GiftPromotionUpdateRecord;
import com.casstime.ec.cloud.values.giftPromotion.GiftRequest;
import com.casstime.ec.cloud.values.giftPromotion.enums.GiftConfigValueEnum;
import com.casstime.ec.cloud.values.giftPromotion.enums.GiftProductValueEnum;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;

/**
 * ClassName: DiscountServiceImpl 
 * Function: (金额促销实现类)
 * Reason: ADD REASON(可选).
 *  
 * @author wu.chen 
 * 2018年2月26日 上午11:02:13
 * @version   
 * @since JDK 1.8
 */
@RestController
public class GiftPromotionServiceRest extends GenericService implements GiftPromotionService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private GiftProductDAOService giftProductDAOService;
	
	@Autowired
	private GiftPromotionDAOService giftPromotionDAOService;
	
	@Autowired
	private GiftPromotionUpdateRecordMapper updateRecordMapper;
	
	@Autowired
	private Userv2Client userv2Client;
	
	@Autowired
	private GiftPromotionFlowingMapper giftPromotionFlowingMapper;
	
	@Autowired
	private DiscountServiceRest discountServiceRest;

	@Override
	public int addOrUpdateGiftProduct(@RequestBody GiftProduct giftProduct,
			@RequestParam("userLoginId") String userLoginId,
			@RequestParam("companyId") String companyId) throws Exception {
		User user = null;
		if (StringUtils.isNotBlank(userLoginId)) {
			user = userv2Client.getUser(userLoginId);
		} else {
			return 0;
		}
		
		if (StringUtils.isNotBlank(giftProduct.getId())) {
			return giftProductDAOService.updateGiftProduct(giftProduct, user);
		} else {
			return giftProductDAOService.addGiftProduct(giftProduct, user);
		}
	}

	@Override
	public PagedModels<GiftProduct> listGiftProducts(@RequestBody GiftRequest giftReq,
			@RequestParam("pageSize") Integer pageSize,
			@RequestParam("pageNum") Integer pageNum) throws Exception {
		SimpleDateFormat simpleformat = new SimpleDateFormat("yyyyMMddHHmmss");
		if (!(giftReq.getMarketPirceMax() == null && giftReq.getMarketPirceMin() == null)) {
			if (giftReq.getMarketPirceMax() == null) {
				giftReq.setMarketPirceMax(100000000.0d);
			}
			if (giftReq.getMarketPirceMin() == null) {
				giftReq.setMarketPirceMin(-10.0d);
			}
		}
		if (!(giftReq.getStartDate() == null && giftReq.getEndDate() == null)) {
			if (giftReq.getStartDate() == null) {
				giftReq.setStartDate(simpleformat.parse("20180101000000"));
			}
			if (giftReq.getEndDate() == null) {
				giftReq.setEndDate(simpleformat.parse("20990101000000"));
			}
		}
		if (StringUtils.isNotBlank(giftReq.getOnsaleStatus()) && giftReq.getOnsaleStatus().equals(GiftProductValueEnum.ONSALE_ALL.getIndex())) {
			giftReq.setOnsaleStatus(null);
		}
		if (StringUtils.isNotBlank(giftReq.getAuditStatus()) && giftReq.getAuditStatus().equals(GiftProductValueEnum.AUDIT_ALL.getIndex())) {
			giftReq.setAuditStatus(null);
		}

		return super.toPagedModels(giftProductDAOService.listGiftProducts(giftReq, pageNum, pageSize));
	}

	@Override
	public int shelvesGiftProduct(@RequestBody List<String> giftIds,
			@RequestParam("onsaleStatus") String onsaleStatus,
			@RequestParam("userLoginId") String userLoginId,
			@RequestParam("companyId") String companyId)
			throws Exception {
		User user = null;
		if (StringUtils.isNotBlank(userLoginId)) {
			user = userv2Client.getUser(userLoginId);
		} else {
			return 0;
		}
		return giftProductDAOService.shelvesGiftProduct(giftIds, onsaleStatus, user);
	}
	
	@Override
	public List<String> validGiftProduct(@RequestBody List<String> giftIds,
			@RequestParam("onsaleStatus") String onsaleStatus,
			@RequestParam("userLoginId") String userLoginId,
			@RequestParam("companyId") String companyId)
			throws Exception {
		User user = null;
		if (StringUtils.isNotBlank(userLoginId)) {
			user = userv2Client.getUser(userLoginId);
		} else {
			return Lists.newArrayList();
		}
		return giftProductDAOService.validGiftProduct(giftIds, onsaleStatus, user);
	}

	@Override
	public int addOrUpdateGiftPromotion(@RequestBody GiftPromotion giftPromotion,
			@RequestParam("userLoginId") String userLoginId,
			@RequestParam("companyId") String companyId) throws Exception {
		User user = null;
		SimpleDateFormat simpleformat = new SimpleDateFormat("yyyyMMddHHmmss");
		giftPromotion.setEffectDate(simpleformat.parse(simpleformat.format(giftPromotion.getEffectDate())));
		giftPromotion.setExpireDate(simpleformat.parse(simpleformat.format(giftPromotion.getExpireDate())));
		if (StringUtils.isNotBlank(userLoginId)) {
			user = userv2Client.getUser(userLoginId);
		} else {
			return 0;
		}
		if (StringUtils.isNotBlank(giftPromotion.getId())) {
			return giftPromotionDAOService.updateGiftPromotion(giftPromotion, user);
		} else {
			return giftPromotionDAOService.addGiftPromotion(giftPromotion, user);
		}
	}

	@Override
	public int stopGiftPromotion(@PathVariable("promotionId") String promotionId,
			@RequestParam("userLoginId") String userLoginId) throws Exception {
		User user = null;
		if (StringUtils.isNotBlank(userLoginId)) {
			user = userv2Client.getUser(userLoginId);
		} else {
			return 0;
		}
		return giftPromotionDAOService.stopGiftPromotion(promotionId, user);
	}

	@Override
	public GiftPromotion findGiftPromotion(@PathVariable("promotionId") String promotionId) throws Exception {
		return giftPromotionDAOService.findGiftPromotion(promotionId);
	}

	@Override
	public PagedModels<GiftPromotionUpdateRecord> listGiftPromotionRecordById(@PathVariable("promotionId") String promotionId,
			   @RequestParam("pageSize") Integer pageSize,
			   @RequestParam("pageNum") Integer pageNum) throws Exception {
		Page<GiftPromotionUpdateRecord> pagedResult = PageHelper.startPage(pageNum, pageSize);
		updateRecordMapper.listGiftPromotionRecords(promotionId);
        return super.toPagedModels(pagedResult);
	}

	@Override
	public PagedModels<GiftPromotion> listGiftPromotionStoreId(@PathVariable("productStoreId") String productStoreId,
			   @RequestParam("pageSize") Integer pageSize,
			   @RequestParam("pageNum") Integer pageNum,
			   @RequestBody GiftPromotionRequest request) throws Exception {
		if (StringUtils.isNotBlank(request.getCustomerType()) && request.getCustomerType().equals(GiftConfigValueEnum.CUSTOMER_ALL.getIndex())) {
			request.setCustomerType(null);
		}
		if (StringUtils.isNotBlank(request.getGiftPromotionType())
				&& request.getGiftPromotionType().equals(GiftConfigValueEnum.GIFT_ALL.getIndex())) {
			request.setGiftPromotionType(null);
		}
		if (StringUtils.isNotBlank(request.getPlatformType()) && request.getPlatformType().equals(DiscountConfigValueEnum.PLATFORM_ALL.getIndex())) {
			request.setPlatformType(null);
		}
		if (StringUtils.isNotBlank(request.getPromotionStatus())
				&& request.getPromotionStatus().equals(DiscountConfigValueEnum.STATUS_ALL.getIndex())) {
			request.setPromotionStatus(null);
		}
		return super.toPagedModels(giftPromotionDAOService.listGiftPromotionStoreId(productStoreId, pageSize, pageNum, request));
	}

	@Override
	public List<GiftProduct> findGiftProductByIds(@RequestBody List<String> giftIds) throws Exception {
		if (CollectionUtils.isEmpty(giftIds)) {
			return Lists.newArrayList();
		}
		return giftProductDAOService.findGiftProductByIds(giftIds);
	}

	@Override
	public int auditGiftProductByIds(@RequestBody List<String> giftIds, @RequestParam("auditStatus") String auditStatus, 
			@RequestParam("auditReason") String auditReason, @RequestParam("userLoginId") String userLoginId) throws Exception {
		User user = null;
		if (StringUtils.isNotBlank(userLoginId)) {
			user = userv2Client.getUser(userLoginId);
		} else {
			return 0;
		}
		if (giftIds != null && giftIds.size() > 0) {
			List<GiftProductAudit> listGiftProductAudit = findGiftProductAuditByGiftIds(giftIds);
			return giftProductDAOService.auditGiftProductByIds(listGiftProductAudit, auditStatus, auditReason, user);
		}
		return 0;
	}
	
	@Override
	public List<GiftProductUpdateRecord> findGiftProductUpdateRecordById(String giftId, String typeId) throws Exception {
		return giftProductDAOService.findGiftProductUpdateRecordById(giftId, typeId);
	}
	
	@Override
	public List<GiftProductAudit> findGiftProductAuditByGiftIds(@RequestBody List<String> giftIds) throws Exception {
		return giftProductDAOService.findGiftProductAuditByGiftIds(giftIds);
	}
	
	@Override
	public List<String> validGiftPromotionProducts(@PathVariable("productStoreId") String productStoreId,
			@RequestParam(name = "giftPromotionId", required = false) String giftPromotionId,
			@RequestParam("startDate") Date startDate,
			@RequestParam("endDate") Date endDate,
			@RequestBody List<String> productIds) throws Exception {
		if (CollectionUtils.isEmpty(productIds)) {
			return Lists.newArrayList();
		} else {
			return giftPromotionDAOService.validGiftPromotionProducts(productStoreId, giftPromotionId, productIds, startDate, endDate);
		}
	}

	@Override
	public PagedModels<GiftPromotionProduct> listGiftPromotionProductsById(@PathVariable("promotionId") String promotionId,
			@RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) throws Exception {
		return super.toPagedModels(giftPromotionDAOService.listGiftPromotionProductsById(promotionId, pageSize, pageNum));
	}

	@Override
	public List<GiftPromotionGiftVO> findGiftProductByProductIds(@RequestBody AmountPromotionQueryRequest queryRequest) throws Exception {
		CassAssert.isNotNull(queryRequest.getCompanyId(), 404, "公司ID不能为空");
		CassAssert.isNotNull(queryRequest.getUserLoginId(), 404, "当前登陆用户不能为空");
		CassAssert.isNotNull(queryRequest.getPlatform(), 404, "当前用户登陆平台不能为空");
		if (CollectionUtils.isEmpty(queryRequest.getProductIds())) {
			logger.error("商品列表不能为空");
			throw new HttpMessageException(404, "商品列表不能为空");
		}
		List<DiscountRuleParam> ruleParams = discountServiceRest.assembleParams(queryRequest);
		List<GiftPromotionGiftVO> retults = giftPromotionDAOService.findGiftPromotionProductByProductIds(queryRequest, ruleParams);
		return retults;	
	}

	@Override
	public GiftDeduction giftDeductionForOrder(@RequestBody GiftDeduction request) throws Exception {
		if (request == null) {
			return null;
		}
		return giftPromotionDAOService.giftDeductionForOrder(request);
		
	}

	@Override
	public void giftFallbackForOrder(@RequestBody List<GiftDeductionGift> gifts) throws Exception {
		if (CollectionUtils.isEmpty(gifts)) {
			return;
		}
		giftPromotionDAOService.giftFallbackForOrder(gifts);
		
	}

	@Override
	public PagedModels<GiftPromotionFlowing> listGiftPromotionFlowStoreId(@PathVariable("productStoreId") String productStoreId,
			   @RequestParam("pageSize") Integer pageSize,
			   @RequestParam("pageNum") Integer pageNum,
			   @RequestBody GiftPromotionFlowingRequest request) throws Exception {
		if (StringUtils.isNotBlank(request.getPlatformType()) 
				&& request.getPlatformType().equals(DiscountConfigValueEnum.PLATFORM_ALL.getIndex())) {
			request.setPlatformType(null);
		}
		Page<GiftPromotionFlowing> pagedResult = PageHelper.startPage(pageNum, pageSize);
		giftPromotionFlowingMapper.listGiftPromotionFlowing(productStoreId, request);
		return super.toPagedModels(pagedResult);
	}

	@Override
	public List<AmountPromotionCompany> listGiftPromotionCompany(@PathVariable("productStoreId") String productStoreId) throws Exception {
		List<AmountPromotionCompany> list = giftPromotionFlowingMapper.listGiftPromotionCompanyBystoreId(productStoreId);
		if (CollectionUtils.isEmpty(list)) {
			return Lists.newArrayList();
		}
		return list;
	}
}
